<%@ page import="java.io.File" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>办公软件下载中心</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

        :root {
            --primary: #83A5D0;
            --primary-dark: #5c7ea8;
            --primary-light: #b5c9e6;
            --primary-bright: #9bbdeb; /* 更明亮的主色调 */
            --primary-lighter: #c5d8f0; /* 更亮的浅色调 */
            --card-bg: rgba(255, 255, 255, 0.92);
            --card-border: rgba(26, 128, 255, 0.18);
            --muted-text: #5c6f88;
        }
        
body {
    font-family: 'Microsoft YaHei', Arial, sans-serif;
    background: url('/bgy.svg') no-repeat center center;
    background-size: cover;
    background-attachment: fixed;
    -moz-background-size: cover;
    -webkit-background-size: cover;
    color: #333;
    min-height: 100vh;
    position: relative;
}

/* 添加半透明遮罩层提升内容可读性 */
body::before {
    content: '';
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(255, 255, 255, 0.3);
    backdrop-filter: blur(2px);
    z-index: -1;
}
        
.container {
    max-width: 1400px;
    margin: 0 auto;
    padding: 30px;
    display: flex;
    gap: 20px;
    position: relative;
    z-index: 1;
}
        
.sidebar {
    width: 280px;
    flex-shrink: 0;
    background: rgba(255,255,255,0.75);
    backdrop-filter: blur(10px);
    border-radius: 16px;
    padding: 10px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}
        
        .main-content {
            flex: 1;
            min-width: 0;
        }
        
.header {
    background: linear-gradient(135deg, var(--primary-bright), var(--primary));
            color: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 20px;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-size: 28px;
            margin-bottom: 10px;
        }
        
.breadcrumb {
    background: rgba(255,255,255,0.92);
    backdrop-filter: blur(10px);
    padding: 15px 20px;
    border-radius: 12px;
    margin-bottom: 20px;
    box-shadow: 0 8px 24px rgba(15, 84, 180, 0.12);
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid rgba(255, 255, 255, 0.5);
}
        
.category-nav {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 16px;
    margin-bottom: 20px;
    box-shadow: 0 8px 24px rgba(15, 84, 180, 0.15);
    overflow: hidden;
    height: fit-content;
    border: 1px solid rgba(255, 255, 255, 0.5);
}
        
.category-header {
    background: linear-gradient(135deg, var(--primary-bright), var(--primary));
            color: white;
            padding: 15px 20px;
            cursor: pointer;
            display: flex;
            align-items: center;
            gap: 10px;
            transition: background 0.2s;
        }
        
.category-header:hover {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
        }
        
        .category-icon {
            font-size: 18px;
        }
        
        .category-title {
            font-size: 16px;
            font-weight: bold;
            flex: 1;
        }
        
        .category-arrow {
            font-size: 12px;
            transition: transform 0.2s;
        }
        
        .category-nav.expanded .category-arrow {
            transform: rotate(180deg);
        }
        
.category-list {
    display: none;
    background: transparent;
}
        
        .category-nav.expanded .category-list {
            display: block;
        }
        
.category-item {
    padding: 14px 20px;
    border-bottom: 1px solid rgba(26,128,255,0.08);
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
        }
        
.category-item:hover {
    background: rgba(26,128,255,0.08);
        }
        
.category-item.active {
    background: rgba(155, 189, 235, 0.3); /* 使用更明亮的主色调 */
            color: #333;
            font-weight: bold;
        }
        
        .category-item.active:hover {
    background: rgba(155, 189, 235, 0.4); /* 使用更明亮的主色调 */
        }
        
        /* 菜单项特殊样式 */
        .menu-item {
            background: rgba(26,128,255,0.15);
            font-weight: bold;
            border-bottom: 2px solid rgba(26,128,255,0.2);
        }
        
        .menu-item:hover {
            background: rgba(26,128,255,0.25);
        }
        
        .menu-item.active {
            background: linear-gradient(135deg, var(--primary-bright), var(--primary));
            color: white;
        }
        
        .menu-item.active:hover {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
        }

        .category-name {
            font-size: 14px;
        }
        
.category-count {
    font-size: 12px;
    color: var(--muted-text);
    background: rgba(26,128,255,0.12);
            padding: 4px 8px;
            border-radius: 12px;
            font-weight: 500;
        }
        
        .expand-icon {
            font-size: 12px;
            color: #6c757d;
            cursor: pointer;
            padding: 4px;
            border-radius: 3px;
            transition: all 0.2s;
            user-select: none;
        }
        
        .expand-icon:hover {
            background: rgba(0,0,0,0.1);
            color: #333;
        }
        
        .category-item.active .expand-icon {
            color: #333;
        }
        
        .category-item.active .expand-icon:hover {
            background: rgba(0,0,0,0.1);
        }
        
        .category-item.active .category-count {
            background: rgba(155, 189, 235, 0.3); /* 使用更明亮的主色调 */
            color: #333;
        }
        
        /* 子分类样式 */
        .sub-category-list {
            background: rgba(255,255,255,0.7);
            border-top: 1px solid rgba(26,128,255,0.08);
        }
        
        .sub-category-item {
            padding: 10px 20px 10px 40px;
            border-bottom: 1px solid #e9ecef;
            cursor: pointer;
            transition: all 0.2s;
            display: flex;
            justify-content: space-between;
            align-items: center;
            position: relative;
        }
        
        .sub-category-item:hover {
            background: rgba(26,128,255,0.08);
        }
        
        .sub-category-item.active {
            background: linear-gradient(135deg, var(--primary-bright), var(--primary));
            color: white;
        }
        
        .sub-category-item.active:hover {
            background: linear-gradient(135deg, var(--primary), var(--primary-dark));
        }
        
        .sub-category-name {
            font-size: 13px;
            color: #666;
        }
        
        .sub-category-item.active .sub-category-name {
            color: white;
        }
        
        .sub-category-item::before {
            content: '';
            position: absolute;
            left: 20px;
            top: 50%;
            transform: translateY(-50%);
            width: 0;
            height: 0;
            border-left: 4px solid #666;
            border-top: 4px solid transparent;
            border-bottom: 4px solid transparent;
        }
        
        .sub-category-item.active::before {
            border-left-color: white;
        }

        .breadcrumb-path {
            color: #666;
            font-size: 14px;
            cursor: default;
            user-select: none;
        }
        
.os-info {
    background: rgba(155, 189, 235, 0.2); /* 使用更明亮的主色调 */
    padding: 8px 12px;
    border-radius: 4px;
    font-size: 12px;
    color: #333;
    display: flex;
    align-items: center;
    gap: 5px;
}
        
        .software-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }
        
.software-card {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 18px;
    padding: 20px;
    box-shadow: 0 8px 24px rgba(15, 84, 180, 0.12);
    transition: transform 0.2s, box-shadow 0.2s;
    border: 1px solid rgba(255, 255, 255, 0.5);
}
        
.software-card:hover {
    transform: translateY(-4px);
    box-shadow: 0 12px 32px rgba(15, 84, 180, 0.2);
    border-color: rgba(131, 165, 208, 0.5);
}
        
        /* 目录卡片特殊样式 */
.directory-card {
    border: 2px solid rgba(26,128,255,0.25);
    background: linear-gradient(135deg, rgba(255,255,255,0.95), rgba(90,176,255,0.2));
}
        
.directory-card:hover {
    border-color: var(--primary);
    background: linear-gradient(135deg, rgba(255,255,255,0.98), rgba(26,128,255,0.28));
}
        
.directory-card .software-icon {
    background: var(--primary);
    font-size: 20px;
}
        
.directory-card .btn-details {
    background: var(--primary);
    color: white;
    border: none;
}
        
.directory-card .btn-details:hover {
    background: var(--primary-dark);
}
        
        .software-header {
            display: flex;
            align-items: center;
            margin-bottom: 15px;
        }
        
.software-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    margin-right: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    font-weight: bold;
    color: #fff;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    background: linear-gradient(135deg, rgba(131, 165, 208, 0.95), rgba(92, 126, 168, 0.95));
    border: 1px solid rgba(255, 255, 255, 0.4);
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.4), 0 12px 24px rgba(92, 126, 168, 0.25);
    overflow: hidden;
}
        
.software-icon img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}
        
        .software-info h3 {
            font-size: 16px;
            margin-bottom: 5px;
            color: #333;
        }
        
.software-desc {
    font-size: 12px;
    color: var(--muted-text);
    margin-bottom: 10px;
}
        
        .software-meta {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 15px;
        }
        
.software-date {
    font-size: 11px;
    color: var(--muted-text);
}
        
        .software-actions {
            display: flex;
            gap: 10px;
        }
        
        .btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.2s;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        
.btn-details {
    background: rgba(155, 189, 235, 0.2); /* 使用更明亮的主色调 */
    color: #333;
    border: 1px solid rgba(155, 189, 235, 0.3);
}
        
.btn-details:hover {
    background: rgba(155, 189, 235, 0.3); /* 使用更明亮的主色调 */
}
        
.btn-download {
    background: linear-gradient(135deg, var(--primary-bright), var(--primary));
            color: white;
            flex: 1;
            border: none;
        }
        
        .btn-download:hover {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
        }
        
        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #999;
        }
        
        .empty-state .icon {
            font-size: 48px;
            margin-bottom: 20px;
        }
        
.back-btn {
    background: linear-gradient(135deg, var(--primary-bright), var(--primary));
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            text-decoration: none;
            display: inline-block;
            margin-top: 20px;
            border: none;
        }
        
.back-btn:hover {
    background: linear-gradient(135deg, var(--primary), var(--primary-dark));
        }
        
        /* 文件类型图标样式（统一冷色系） */
        .icon-image,
        .icon-document,
        .icon-code {
            background: linear-gradient(135deg, rgba(191, 210, 236, 0.95), rgba(131, 165, 208, 0.95));
        }

        .icon-spreadsheet,
        .icon-presentation,
        .icon-executable {
            background: linear-gradient(135deg, rgba(168, 194, 228, 0.95), rgba(111, 145, 190, 0.95));
        }

        .icon-archive,
        .icon-media,
        .icon-file {
            background: linear-gradient(135deg, rgba(149, 180, 220, 0.95), rgba(97, 133, 179, 0.95));
        }
        
        /* 响应式设计 */
        @media (max-width: 768px) {
            .container {
                flex-direction: column;
                padding: 10px;
            }
            
            .sidebar {
                width: 100%;
                margin-bottom: 20px;
            }
            
            .software-grid {
                grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
                gap: 15px;
            }
        }
        
        @media (max-width: 480px) {
            .software-grid {
                grid-template-columns: 1fr;
            }
            
            .breadcrumb {
                flex-direction: column;
                gap: 10px;
            }
            
            .os-info {
                align-self: flex-start;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 左侧分类导航 -->
        <div class="sidebar">
            <div class="category-nav" id="categoryNav">
                <div class="category-header">
                    <span class="category-icon">📁</span>
                    <span class="category-title">自助服务</span>
                    <span class="category-arrow">▼</span>
                </div>
                <div class="category-list" id="categoryList">
                    <!-- 动态加载分类 -->
                </div>
            </div>
        </div>
        
        <!-- 右侧主要内容区域 -->
        <div class="main-content">
            <div class="header">
                <h1>自助服务</h1>
            </div>
            
            <div class="breadcrumb">
                <div class="breadcrumb-path" id="breadcrumbPath">
                    您的位置：首页 > 自助服务
                </div>
                <div class="os-info">
                    ⭐ 当前操作系统是 Windows 10/11 64位
                </div>
            </div>
            
            <div class="software-grid" id="softwareGrid">
                <div class="empty-state">
                    <div class="icon">📁</div>
                    <p>正在加载文件列表...</p>
                </div>
            </div>
            
            
            <!-- 目录配置面板 -->
            <div id="configPanel" style="display: none; margin-top: 20px; padding: 15px; background: rgba(26,128,255,0.08); border: 1px solid rgba(26,128,255,0.25); border-radius: 10px;">
                <h4 style="margin-bottom: 10px; color: var(--primary-dark);">⚙️ 目录配置</h4>
                <button onclick="toggleConfigPanel()" style="float: right; background: var(--primary); color: white; border: none; padding: 5px 10px; border-radius: 6px; cursor: pointer;">关闭</button>
                <div style="margin-bottom: 10px;">
                    <label style="display: block; margin-bottom: 5px; font-weight: bold;">已知目录列表（每行一个）:</label>
                    <textarea id="knownDirectories" rows="5" style="width: 100%; padding: 8px; border: 1px solid #ccc; border-radius: 4px; font-family: monospace;">outlook_mail</textarea>
                </div>
                <button onclick="updateDirectoryConfig()" style="background: var(--primary); color: white; border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer;">更新配置</button>
                <button onclick="resetDirectoryConfig()" style="background: rgba(26,128,255,0.15); color: var(--primary-dark); border: none; padding: 8px 16px; border-radius: 6px; cursor: pointer; margin-left: 10px;">重置</button>
            </div>
        </div>
    </div>

    <!-- 内联配置脚本 -->
    <script>
    // 后端API配置
    // 通过Tomcat代理访问后端服务，避免跨域问题
    const API_CONFIG = {
        // 通过Tomcat代理访问后端服务
        // 请求会被代理到 http://localhost:8088
        // 注意：需要包含 /download 前缀，因为 ROOT 应用的路径是 /download
        BASE_URL: '/download/api',
        
        // 文档API基础URL
        DOC_BASE_URL: '/download/api/public/doc',

        // API端点
        ENDPOINTS: {
            CATEGORIES: '/public/categories',
            FILES: '/public/files',
            DOWNLOAD: '/public/download',
            DOWNLOAD_BY_PATH: '/public/downloadByPath'
        },
        
        // 文档API端点
        DOC_ENDPOINTS: {
            CATEGORIES: '/categories',
            FILES: '/files',
            DOWNLOAD: '/download',
            DOWNLOAD_BY_PATH: '/downloadByPath'
        }
    };

        // 获取完整的API URL
        function getApiUrl(endpoint) {
            return API_CONFIG.BASE_URL + endpoint;
        }
        
        // 获取文档API URL
        function getDocApiUrl(endpoint) {
            return API_CONFIG.DOC_BASE_URL + endpoint;
        }

        // 获取分类列表API URL
        function getCategoriesUrl() {
            // 根据当前菜单类型返回对应的URL
            if (currentMenuType === 'document') {
                return getDocApiUrl(API_CONFIG.DOC_ENDPOINTS.CATEGORIES);
            }
            return getApiUrl(API_CONFIG.ENDPOINTS.CATEGORIES);
        }

        // 获取文件列表API URL
        function getFilesUrl(path = '') {
            let url;
            if (currentMenuType === 'document') {
                url = getDocApiUrl(API_CONFIG.DOC_ENDPOINTS.FILES);
            } else {
                url = getApiUrl(API_CONFIG.ENDPOINTS.FILES);
            }
            return path ? url + '?path=' + encodeURIComponent(path) : url;
        }

        // 获取下载API URL
        function getDownloadUrl(fileId) {
            if (currentMenuType === 'document') {
                return getDocApiUrl(API_CONFIG.DOC_ENDPOINTS.DOWNLOAD) + '/' + fileId;
            }
            return getApiUrl(API_CONFIG.ENDPOINTS.DOWNLOAD) + '/' + fileId;
        }

        // 获取按路径下载API URL
        function getDownloadByPathUrl(filePath, fileName = '') {
            let url;
            if (currentMenuType === 'document') {
                url = getDocApiUrl(API_CONFIG.DOC_ENDPOINTS.DOWNLOAD_BY_PATH);
            } else {
                url = getApiUrl(API_CONFIG.ENDPOINTS.DOWNLOAD_BY_PATH);
            }

            // 对文件路径进行URL编码，确保中文字符正确处理
            let encodedFilePath = filePath;
            try {
                // 如果路径已经是编码的，先解码再重新编码
                if (filePath.includes('%')) {
                    encodedFilePath = decodeURIComponent(filePath);
                }
                encodedFilePath = encodeURIComponent(encodedFilePath);
            } catch (e) {
                // 如果解码失败，直接编码原始路径
                encodedFilePath = encodeURIComponent(filePath);
            }

            let params = 'filePath=' + encodedFilePath;
            if (fileName) {
                params += '&fileName=' + encodeURIComponent(fileName);
            }

            const finalUrl = url + '?' + params;

            return finalUrl;
        }
    </script>

    <script>
        let currentCategory = null;
        let categories = [];
        // 当前菜单类型：software(软件) 或 document(文档)
        let currentMenuType = 'software';
        // 菜单配置
        const menus = [
            { id: 'software', name: '常用软件', path: '首页 > 自助服务 > 常用软件' },
            { id: 'document', name: '文档库', path: '首页 > 自助服务 > 文档库' }
        ];

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            // 默认展开分类导航
            const categoryNav = document.getElementById('categoryNav');
            if (categoryNav) {
                categoryNav.classList.add('expanded');
            }

            // 渲染菜单
            renderMenus();
            
            // 默认加载软件菜单
            selectMenu('software');
        });

        // 渲染菜单
        function renderMenus() {
            const categoryList = document.getElementById('categoryList');
            let html = '';
            
            // 渲染子菜单
            menus.forEach(menu => {
                const isActive = menu.id === currentMenuType;
                html += '<div class="category-item ' + (isActive ? 'active' : '') + '" data-menu-id="' + menu.id + '">' +
                        '<span class="category-name">' + menu.name + '</span>' +
                        '</div>';
            });
            
            categoryList.innerHTML = html;
            
            // 重新绑定菜单点击事件
            bindMenuEvents();
        }

        // 绑定菜单事件
        function bindMenuEvents() {
            // 移除之前的事件监听器
            const categoryNav = document.getElementById('categoryNav');
            if (categoryNav) {
                categoryNav.removeEventListener('click', handleCategoryClick);
                // 添加新的事件监听器
                categoryNav.addEventListener('click', handleCategoryClick);
            }
        }

        // 存储菜单展开状态
        let menuExpandState = {};
        
        // 存储当前活动的菜单ID
        let activeMenuId = null;

        // 处理菜单点击事件
        function handleCategoryClick(e) {
            // 检查是否点击了面包屑区域
            if (e.target.closest('.breadcrumb') || e.target.closest('.breadcrumb-path')) {
                e.stopPropagation();
                return;
            }

            // 检查是否点击了主内容区域
            if (e.target.closest('.main-content')) {
                e.stopPropagation();
                return;
            }

            // 只有点击分类导航区域才处理
            if (e.target.closest('.category-header')) {
                toggleCategoryNav();
            } else if (e.target.closest('.category-item[data-menu-id]')) {
                // 处理菜单点击
                const categoryItem = e.target.closest('.category-item[data-menu-id]');
                const menuId = categoryItem.dataset.menuId;
                
                // 更新活动菜单ID
                activeMenuId = menuId;
                
                // 检查是否点击了展开图标
                if (e.target.closest('.expand-icon')) {
                    // 点击展开图标：切换子分类显示状态
                    // 更新状态
                    menuExpandState[menuId] = !menuExpandState[menuId];
                    toggleSubCategoriesByMenuId(menuId);
                } else {
                    // 点击菜单项本身：切换子分类的展开/折叠状态，然后选择菜单
                    // 更新状态
                    menuExpandState[menuId] = !menuExpandState[menuId];
                    toggleSubCategoriesByMenuId(menuId);
                    
                    // 选择菜单
                    selectMenu(menuId);
                }
            } else if (e.target.closest('.sub-category-item')) {
                // 处理子分类点击
                const categoryItem = e.target.closest('.sub-category-item');
                const categoryId = categoryItem.dataset.categoryId;
                
                // 检查是否点击了展开图标
                if (e.target.closest('.expand-icon')) {
                    // 切换子目录显示状态
                    toggleSubDirectories(categoryItem);
                } else {
                    // 选择分类
                    selectCategory(categoryId);
                }
            } else if (e.target.closest('.sub-directory-item')) {
                // 处理子目录点击
                const directoryItem = e.target.closest('.sub-directory-item');
                const dirId = directoryItem.dataset.dirId;
                const dirName = directoryItem.dataset.dirName;
                const categoryId = directoryItem.dataset.categoryId;
                enterDirectory(dirId, dirName, categoryId);
            }
        }

        // 选择菜单
        function selectMenu(menuId) {
            // 更新当前菜单类型
            currentMenuType = menuId;
            
            // 更新活动菜单ID
            activeMenuId = menuId;
            
            // 初始化菜单展开状态（如果尚未初始化）
            if (menuExpandState[menuId] === undefined) {
                menuExpandState[menuId] = false;  // 默认折叠状态
            }
            
            // 保存当前菜单的展开状态，避免在分类加载后被重置
            const currentExpandState = menuExpandState[menuId];
            
            // 更新活动状态
            document.querySelectorAll('.category-item').forEach(item => {
                item.classList.remove('active');
            });

            const selectedItem = document.querySelector('[data-menu-id="' + menuId + '"]');
            if (selectedItem) {
                selectedItem.classList.add('active');
            }
            
            // 更新页面标题
            const header = document.querySelector('.header h1');
            const selectedMenu = menus.find(menu => menu.id === menuId);
            if (header && selectedMenu) {
                header.textContent = selectedMenu.name;
            }
            
            // 更新面包屑
            updateBreadcrumbForMenu(menuId);
            
            // 加载分类和文件列表
            loadCategories(() => {
                // 分类加载完成后，确保当前菜单的展开状态正确
                // 恢复菜单的展开状态
                menuExpandState[menuId] = currentExpandState;
                setTimeout(() => {
                    toggleSubCategoriesByMenuId(menuId);
                }, 50);
            });
            loadFileList();
        }

        // 更新面包屑导航
        function updateBreadcrumbForMenu(menuId) {
            const breadcrumbPath = document.getElementById('breadcrumbPath');
            const selectedMenu = menus.find(menu => menu.id === menuId);
            if (breadcrumbPath && selectedMenu) {
                breadcrumbPath.textContent = selectedMenu.path;
            }
        }

        // 更新面包屑（保持原有功能）
        function updateBreadcrumb(categoryName) {
            const breadcrumbPath = document.getElementById('breadcrumbPath');
            const selectedMenu = menus.find(menu => menu.id === currentMenuType);
            if (breadcrumbPath && selectedMenu) {
                breadcrumbPath.textContent = selectedMenu.path + (categoryName ? ' > ' + categoryName : '');
            }
        }

        // 更新面包屑（带历史记录）
        function updateBreadcrumbWithHistory(categoryName, dirName) {
            const breadcrumbPath = document.getElementById('breadcrumbPath');
            const selectedMenu = menus.find(menu => menu.id === currentMenuType);
            let path = selectedMenu ? selectedMenu.path : '首页 > 自助服务';
            
            if (categoryName) {
                path += ' > ' + categoryName;
            }

            if (dirName && dirName !== categoryName) {
                path += ' > ' + dirName;
            }

            breadcrumbPath.innerHTML = path + ' <a href="#" onclick="goBack()" style="color: #2196f3; text-decoration: none; margin-left: 10px;">← 返回</a>';
        }

        // 更新面包屑（简单版本）
        function updateBreadcrumbSimple(categoryName, dirName) {
            const breadcrumbPath = document.getElementById('breadcrumbPath');
            const selectedMenu = menus.find(menu => menu.id === currentMenuType);
            let path = selectedMenu ? selectedMenu.path : '首页 > 自助服务';
            
            if (categoryName) {
                path += ' > ' + categoryName;
            }

            if (dirName && dirName !== categoryName) {
                path += ' > ' + dirName;
            }

            breadcrumbPath.innerHTML = path + ' <a href="#" onclick="goBack()" style="color: #2196f3; text-decoration: none; margin-left: 10px;">← 返回</a>';
        }

        function loadCategories(callback) {
            fetch(getCategoriesUrl(), {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('HTTP error! status: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 200) {
                        categories = data.data;
                        renderCategories();
                        if (callback) {
                            callback();
                        }
        } else {
                        console.error('加载分类失败：', data.msg);
                        showCategoryError('加载分类失败：' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error loading categories:', error);
                    showCategoryError('网络错误: ' + error.message + '，请检查后端服务是否正常运行');
                });
        }


        function showCategoryError(message) {
            const categoryList = document.getElementById('categoryList');
            categoryList.innerHTML = '<div style="padding: 20px; text-align: center; color: #999;">' + message + '</div>';
        }

        // 存储当前分类的子目录
        let currentSubDirectories = [];

        function renderCategories() {
            const categoryList = document.getElementById('categoryList');
            let html = '';

            // 渲染菜单项（常用软件、文档库等）作为可展开的树形节点
            menus.forEach(menu => {
                const isActive = menu.id === currentMenuType;
                // 检查是否有子分类
                const hasSubCategories = categories && categories.length > 0;
                
                html += '<div class="category-item menu-item ' + (isActive ? 'active' : '') + '" data-menu-id="' + menu.id + '" data-category-type="menu">' +
                        '<span class="category-name">' + menu.name + '</span>' +
                        (hasSubCategories ? '<span class="expand-icon">▼</span>' : '') +
                        '</div>';
                
                // 如果有子分类，添加子分类列表（默认折叠）
                if (hasSubCategories) {
                    html += '<div class="sub-category-list" style="display: none;">';
                    categories.forEach(category => {
                        // 处理可能的乱码问题
                        let categoryName = category.name || '未知分类';
                        if (categoryName.includes('?')) {
                            // 如果包含乱码，尝试使用ID作为显示名称
                            categoryName = '分类' + category.id;
                        }

                        const hasSubDirs = category.subDirectories && category.subDirectories.length > 0;

                        html += '<div class="sub-category-item" data-category-id="' + category.id + '">' +
                                '<span class="sub-category-name">' + categoryName + '</span>' +
                                (hasSubDirs ? '<span class="category-count">' + (category.size || 0) + '</span><span class="expand-icon">▼</span>' : '') +
                                '</div>';

                        // 如果有子目录，添加子目录列表（默认折叠）
                        if (hasSubDirs) {
                            html += '<div class="sub-directory-list" style="display: none;">';
                            category.subDirectories.forEach(dir => {
                                html += '<div class="sub-directory-item" data-dir-id="' + dir.id + '" data-dir-name="' + dir.name + '" data-category-id="' + category.id + '">' +
                                        '<span class="sub-directory-name">📁 ' + dir.name + '</span>' +
                                '</div>';
                            });
                            html += '</div>';
                        }
                    });
                    html += '</div>';
                }
            });

            categoryList.innerHTML = html;

            // 重新绑定分类点击事件
            bindCategoryEvents();
        }

        function bindCategoryEvents() {
            const categoryNav = document.getElementById('categoryNav');
            if (categoryNav) {
                // 移除之前的事件监听器
                categoryNav.removeEventListener('click', handleCategoryClick);
                // 添加新的事件监听器，使用事件捕获来更精确地控制
                categoryNav.addEventListener('click', handleCategoryClick, true);
            }
        }

        function toggleCategoryNav() {
            const categoryNav = document.getElementById('categoryNav');
            categoryNav.classList.toggle('expanded');
        }


        
        // 切换菜单项的展开状态（用于菜单项）
        function toggleMenuCategories(menuItem) {
            // 对于菜单项，我们不需要实际展开子目录，因为子目录是通过selectMenu动态加载的
            // 这里可以添加其他菜单相关的逻辑
        }

        // 切换子分类显示状态（通过菜单ID）
        function toggleSubCategoriesByMenuId(menuId) {
            // 查找菜单项
            const categoryItem = document.querySelector('[data-menu-id="' + menuId + '"]');
            if (categoryItem) {
                // 查找下一个兄弟元素，应该是子分类列表
                const subCategoryList = categoryItem.nextElementSibling;
                const expandIcon = categoryItem.querySelector('.expand-icon');
                
                if (subCategoryList && subCategoryList.classList.contains('sub-category-list') && expandIcon) {
                    // 使用状态变量来决定是展开还是折叠
                    const shouldExpand = menuExpandState[menuId] || false;
                    
                    if (shouldExpand) {
                        // 展开子分类
                        subCategoryList.style.display = 'block';
                        expandIcon.textContent = '▲';
                    } else {
                        // 折叠子分类
                        subCategoryList.style.display = 'none';
                        expandIcon.textContent = '▼';
                    }
                }
            }
        }

        function selectCategory(categoryId) {
            // 检查分类数据是否已加载
            if (!categories || categories.length === 0) {
                console.warn('分类数据尚未加载完成');
                return;
            }

            // 更新活动状态（只更新分类，不更新菜单）
            document.querySelectorAll('.category-item[data-category-id]').forEach(item => {
                item.classList.remove('active');
            });

            // 清除所有子目录的激活状态
            document.querySelectorAll('.sub-category-item').forEach(item => {
                item.classList.remove('active');
            });

            const selectedItem = document.querySelector('[data-category-id="' + categoryId + '"]');
            if (selectedItem) {
                selectedItem.classList.add('active');

                // 如果有子目录，切换显示状态
                const subCategoryList = selectedItem.nextElementSibling;
                const expandIcon = selectedItem.querySelector('.expand-icon');
                if (subCategoryList && subCategoryList.classList.contains('sub-category-list') && expandIcon) {
                    if (subCategoryList.style.display === 'none' || subCategoryList.style.display === '') {
                        // 展开子目录
                        subCategoryList.style.display = 'block';
                        expandIcon.textContent = '▲';
                    } else {
                        // 折叠子目录
                        subCategoryList.style.display = 'none';
                        expandIcon.textContent = '▼';
                    }
                }
            } else {
                console.warn('未找到分类项，ID:', categoryId);
                return;
            }

            // 找到选中的分类
            const category = categories.find(cat => cat.id == categoryId);
            if (category) {
                currentCategory = category;

                // 检查是否是"常用软件"分类，如果是则显示所有文件
                if (category.name && (category.name.includes('常用软件') || category.name.includes('Common Software'))) {
                    updateBreadcrumb('常用软件');
                    loadFileList(null); // 传入null表示显示所有文件
                } else {
                    updateBreadcrumb(category.name);

                    // 检查是否有预加载的子目录
                    if (category.subDirectories && category.subDirectories.length > 0) {
                        // 有预加载的子目录，直接显示分类内容
                        loadDirectoryStructureWithPreloadedData(categoryId, category.subDirectories);
                    } else {
                        // 没有预加载的子目录，需要加载目录结构
                        loadDirectoryStructureWithExpand(categoryId);
                    }
                }
            } else {
                console.warn('未找到分类数据，ID:', categoryId);
            }
        }

        // 面包屑历史记录
        let breadcrumbHistory = [];

        function updateBreadcrumb(categoryName) {
            const breadcrumbPath = document.getElementById('breadcrumbPath');
            const selectedMenu = menus.find(menu => menu.id === currentMenuType);
            if (breadcrumbPath && selectedMenu) {
                breadcrumbPath.textContent = selectedMenu.path + (categoryName ? ' > ' + categoryName : '');
            }
        }

        // 新增：更新面包屑（带历史记录）
        function updateBreadcrumbWithHistory(categoryName, dirName) {
            const breadcrumbPath = document.getElementById('breadcrumbPath');
            const selectedMenu = menus.find(menu => menu.id === currentMenuType);
            let path = selectedMenu ? selectedMenu.path : '首页 > 自助服务';
            
            if (categoryName) {
                path += ' > ' + categoryName;
            }

            if (dirName && dirName !== categoryName) {
                path += ' > ' + dirName;
            }

            breadcrumbPath.innerHTML = path + ' <a href="#" onclick="goBack()" style="color: #2196f3; text-decoration: none; margin-left: 10px;">← 返回</a>';
        }

        // 新增：更新面包屑（简单版本）
        function updateBreadcrumbSimple(categoryName, dirName) {
            const breadcrumbPath = document.getElementById('breadcrumbPath');
            const selectedMenu = menus.find(menu => menu.id === currentMenuType);
            let path = selectedMenu ? selectedMenu.path : '首页 > 自助服务';
            
            if (categoryName) {
                path += ' > ' + categoryName;
            }

            if (dirName && dirName !== categoryName) {
                path += ' > ' + dirName;
            }

            breadcrumbPath.innerHTML = path + ' <a href="#" onclick="goBack()" style="color: #2196f3; text-decoration: none; margin-left: 10px;">← 返回</a>';
        }

        // 新增：返回功能
        function goBack() {
            // 简单返回逻辑：直接返回到分类的根目录
            updateBreadcrumb(currentCategory.name);
            loadDirectoryStructure(currentCategory.id);
        }

        // 新增：加载目录结构（带自动展开）
        function loadDirectoryStructureWithExpand(categoryId) {
            // 显示加载状态
            const grid = document.getElementById('softwareGrid');
            grid.innerHTML = '<div class="empty-state"><div class="icon">📁</div><p>正在加载目录结构...</p></div>';

            // 调用后端API获取目录结构
            const path = 'category_' + categoryId;

            // 使用现有的 /public/files 接口，无需额外接口
            fetch(getFilesUrl(path))
                .then(response => {
                    return response.json();
                })
                .then(data => {

                    if (data.code === 200) {

                        // 后端API现在会返回目录信息，使用正常的识别逻辑
                        const directories = data.data.filter(item => {
                            // 多种目录识别方式
                            return item.isDir === true ||
                                   item.type === 'directory' ||
                                   item.isDirectory === true ||
                                   item.fileType === 'directory' ||
                                   (item.suffix === '' && !item.name.includes('.')) || // 没有扩展名且不包含点号
                                   item.name === 'outlook_mail' || // 特殊处理已知目录
                                   (item.size === 0 && !item.name.includes('.')) || // 大小为0且无扩展名
                                   item.url && item.url.endsWith('/'); // URL以斜杠结尾
                        });

                        const files = data.data.filter(item => {
                            // 排除目录的文件
                            return !(item.isDir === true ||
                                   item.type === 'directory' ||
                                   item.isDirectory === true ||
                                   item.fileType === 'directory' ||
                                   (item.suffix === '' && !item.name.includes('.')) ||
                                   item.name === 'outlook_mail' ||
                                   (item.size === 0 && !item.name.includes('.')) ||
                                   item.url && item.url.endsWith('/'));
                        });


                        if (directories.length > 0) {
                            // 如果有目录，在左侧导航显示子目录，主内容区域只显示文件
                            currentSubDirectories = directories;
                            renderSubDirectories(directories, categoryId);
                            renderFileList(files);
                        } else {
                            // 如果没有目录，直接显示文件
                            renderFileList(files);
                        }
                    } else {
                        showError('加载失败：' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('网络错误，请检查连接');
                });
        }

        // 新增：使用预加载数据加载目录结构
        function loadDirectoryStructureWithPreloadedData(categoryId, directories) {
            // 显示加载状态
            const grid = document.getElementById('softwareGrid');
            grid.innerHTML = '<div class="empty-state"><div class="icon">📁</div><p>正在加载目录结构...</p></div>';

            // 调用后端API获取文件列表
            const path = 'category_' + categoryId;

            fetch(getFilesUrl(path))
                .then(response => response.json())
                .then(data => {
                    if (data.code === 200) {
                        // 过滤出文件
                        const files = data.data.filter(item => {
                            return !(item.isDir === true ||
                                   item.type === 'directory' ||
                                   item.isDirectory === true ||
                                   item.fileType === 'directory' ||
                                   (item.suffix === '' && !item.name.includes('.')) ||
                                   item.name === 'outlook_mail' ||
                                   (item.size === 0 && !item.name.includes('.')) ||
                                   item.url && item.url.endsWith('/'));
                        });

                        // 主内容区域只显示文件
                        if (files.length > 0) {
                            renderFileList(files);
                        } else {
                            showEmptyState('该分类下暂无文件');
                        }
                    } else {
                        showError('加载失败：' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('网络错误，请检查连接');
                });
        }

        // 新增：加载目录结构
        function loadDirectoryStructure(categoryId) {

            // 显示加载状态
            const grid = document.getElementById('softwareGrid');
            grid.innerHTML = '<div class="empty-state"><div class="icon">📁</div><p>正在加载目录结构...</p></div>';

            // 调用后端API获取目录结构
            const path = 'category_' + categoryId;

            // 使用现有的 /public/files 接口，无需额外接口
            fetch(getFilesUrl(path))
                .then(response => {
                    return response.json();
                })
                .then(data => {

                    if (data.code === 200) {

                        // 后端API现在会返回目录信息，使用正常的识别逻辑
                        const directories = data.data.filter(item => {
                            // 多种目录识别方式
                            return item.isDir === true ||
                                   item.type === 'directory' ||
                                   item.isDirectory === true ||
                                   item.fileType === 'directory' ||
                                   (item.suffix === '' && !item.name.includes('.')) || // 没有扩展名且不包含点号
                                   item.name === 'outlook_mail' || // 特殊处理已知目录
                                   (item.size === 0 && !item.name.includes('.')) || // 大小为0且无扩展名
                                   item.url && item.url.endsWith('/'); // URL以斜杠结尾
                        });

                        const files = data.data.filter(item => {
                            // 排除目录的文件
                            return !(item.isDir === true ||
                                   item.type === 'directory' ||
                                   item.isDirectory === true ||
                                   item.fileType === 'directory' ||
                                   (item.suffix === '' && !item.name.includes('.')) ||
                                   item.name === 'outlook_mail' ||
                                   (item.size === 0 && !item.name.includes('.')) ||
                                   item.url && item.url.endsWith('/'));
                        });


                        if (directories.length > 0) {
                            // 如果有目录，在左侧导航显示子目录，主内容区域只显示文件
                            currentSubDirectories = directories;
                            renderSubDirectories(directories, categoryId);
                            renderFileList(files);
                        } else {
                            // 如果没有目录，直接显示文件
                            renderFileList(files);
                        }
                    } else {
                        showError('加载失败：' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('网络错误，请检查连接');
                });
        }

        // 新增：渲染目录结构
        function renderDirectoryStructure(directories, files, categoryId) {
            const grid = document.getElementById('softwareGrid');
            let html = '';

            // 不渲染目录卡片，目录只显示在左侧导航中

            // 如果有文件，也显示文件
            if (files.length > 0) {
                html += '<div class="software-card" style="grid-column: 1 / -1; background: var(--card-bg); border: 2px dashed rgba(26,128,255,0.2);">' +
                        '<div style="text-align: center; padding: 20px;">' +
                        '<h3 style="color: var(--muted-text); margin-bottom: 15px;">📄 该分类下的文件</h3>' +
                        '<div style="display: flex; flex-wrap: wrap; gap: 10px; justify-content: center;">';

                files.forEach(file => {
                    const iconClass = getFileIconClass(file.type);
                    const fileSize = formatFileSize(file.size);
                    
                    // 生成图标HTML，优先使用PNG图标，如果没有则使用默认的首字母图标
                    const iconName = file.name.replace(/\.[^/.]+$/, ""); // 去除文件扩展名
                    const iconHtml = '<img src="/icon/' + iconName + '.png" onerror="this.onerror=null; this.parentElement.innerHTML=\'' + getFileIconText(file.suffix) + '\';">';

                    html += '<div style="background: white; padding: 10px; border-radius: 6px; box-shadow: 0 1px 3px rgba(0,0,0,0.1); min-width: 200px;">' +
                            '<div style="display: flex; align-items: center; margin-bottom: 8px;">' +
                            '<div class="software-icon ' + iconClass + '" style="width: 32px; height: 32px; font-size: 16px; margin-right: 10px;">' + iconHtml + '</div>' +
                            '<div>' +
                            '<div style="font-weight: bold; font-size: 14px;">' + file.name + '</div>' +
                            '<div style="font-size: 12px; color: #666;">' + fileSize + ' • ' + file.suffix.toUpperCase() + '</div>' +
                            '</div>' +
                            '</div>' +
                            '<div style="text-align: right;">' +
                            '<a href="' + getDownloadByPathUrl(file.url, file.name) + '" ' +
                            'class="btn btn-download" download="' + file.name + '" style="padding: 6px 12px; font-size: 12px;">下载</a>' +
                            '</div>' +
                            '</div>';
                });

                html += '</div></div></div>';
            } else if (directories.length > 0) {
                // 如果没有文件但有目录，显示提示信息
                html += '<div class="software-card" style="grid-column: 1 / -1; background: var(--card-bg); border: 2px dashed rgba(26,128,255,0.2);">' +
                        '<div style="text-align: center; padding: 20px;">' +
                        '<h3 style="color: var(--muted-text); margin-bottom: 15px;">📁 该分类下只有目录，没有文件</h3>' +
                        '<p style="color: var(--muted-text); font-size: 14px;">点击上方的目录可以进入查看内容</p>' +
                        '</div></div>';
            }

            grid.innerHTML = html;

            // 绑定目录点击事件
            bindDirectoryEvents();
        }

        // 新增：进入目录
        function enterDirectory(dirId, dirName, categoryId) {
            // 确保使用正确的分类信息
            const targetCategory = categories.find(cat => cat.id == categoryId);
            if (targetCategory) {
                currentCategory = targetCategory;
            }

            // 更新左侧导航状态
            updateSubDirectoryActiveState(dirName);

            // 更新面包屑（简单版本）
            updateBreadcrumbSimple(currentCategory.name, dirName);

            // 构建正确的路径格式：category_66
            const fullPath = 'category_' + dirId;

            // 加载目录下的文件
            loadFileListInDirectory(fullPath, categoryId);
        }

        // 新增：更新子目录激活状态
        function updateSubDirectoryActiveState(activeDirName) {
            // 移除所有子目录的激活状态
            document.querySelectorAll('.sub-category-item').forEach(item => {
                item.classList.remove('active');
            });

            // 激活当前选中的子目录
            document.querySelectorAll('.sub-category-item').forEach(item => {
                const dirName = item.querySelector('.sub-category-name').textContent.replace('📁 ', '');
                if (dirName === activeDirName) {
                    item.classList.add('active');
                }
            });
        }

        // 新增：加载目录下的文件
        function loadFileListInDirectory(dirPath, categoryId) {

            // 显示加载状态
            const grid = document.getElementById('softwareGrid');
            grid.innerHTML = '<div class="empty-state"><div class="icon">📁</div><p>正在加载文件...</p></div>';

            // 使用相同的 /public/files 接口，传入目录路径
            fetch(getFilesUrl(dirPath))
                .then(response => {
                    return response.json();
                })
                .then(data => {
                    if (data.code === 200) {
                        // 再次分离目录和文件
                        const directories = data.data.filter(item => {
                            return item.isDir === true ||
                                   item.type === 'directory' ||
                                   item.isDirectory === true ||
                                   item.fileType === 'directory' ||
                                   (item.suffix === '' && !item.name.includes('.')) ||
                                   (item.size === 0 && !item.name.includes('.')) ||
                                   item.url && item.url.endsWith('/');
                        });

                        const files = data.data.filter(item => {
                            return !(item.isDir === true ||
                                   item.type === 'directory' ||
                                   item.isDirectory === true ||
                                   item.fileType === 'directory' ||
                                   (item.suffix === '' && !item.name.includes('.')) ||
                                   (item.size === 0 && !item.name.includes('.')) ||
                                   item.url && item.url.endsWith('/'));
                        });

                        if (directories.length > 0) {
                            // 如果还有子目录，显示目录结构
                            renderDirectoryStructure(directories, files, categoryId);
                        } else {
                            // 如果没有子目录，只显示文件
                            renderFileList(files);
                        }
                    } else {
                        showError('加载失败：' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('网络错误，请检查连接');
                });
        }

        // 新增：绑定目录事件
        function bindDirectoryEvents() {
            // 目录卡片点击事件
            document.querySelectorAll('.directory-card').forEach(card => {
                card.addEventListener('click', function(e) {
                    // 如果点击的是按钮，不触发卡片点击
                    if (e.target.closest('.btn')) {
                        return;
                    }

                    const dirPath = this.dataset.dirPath;
                    const dirName = this.querySelector('h3').textContent;
                    const categoryId = this.dataset.categoryId;

                    enterDirectory(dirPath, dirName, categoryId);
                });
            });
        }

        function loadFileList(categoryId = null) {
            // 更新面包屑导航
            const selectedMenu = menus.find(menu => menu.id === currentMenuType);
            if (selectedMenu) {
                const breadcrumbPath = document.getElementById('breadcrumbPath');
                if (breadcrumbPath) {
                    breadcrumbPath.textContent = selectedMenu.path;
                }
            }

            const grid = document.getElementById('softwareGrid');
            grid.innerHTML = '<div class="empty-state"><div class="icon">📁</div><p>正在加载文件列表...</p></div>';

            let path = '';
            if (categoryId === null) {
                // 显示所有文件
                path = '';
            } else if (categoryId) {
                // 显示特定分类的文件
                path = 'category_' + categoryId;
            } else {
                // 默认显示所有文件
                path = '';
            }

            fetch(getFilesUrl(path), {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('HTTP error! status: ' + response.status);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.code === 200) {
                        // 过滤出文件数据，排除目录
                        const files = data.data.filter(item => {
                            return !(item.isDir === true ||
                                   item.type === 'directory' ||
                                   item.isDirectory === true ||
                                   item.fileType === 'directory' ||
                                   (item.suffix === '' && !item.name.includes('.')) ||
                                   (item.size === 0 && !item.name.includes('.')) ||
                                   item.url === null ||
                                   item.url === undefined);
                        });
                        renderFileList(files);
                    } else {
                        showError('加载失败：' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    showError('网络错误: ' + error.message + '，请检查后端服务是否正常运行');
                });
        }
        
        function renderFileList(files) {
            const grid = document.getElementById('softwareGrid');
            
            if (files.length === 0) {
                grid.innerHTML = '<div class="empty-state"><div class="icon">📁</div><p>暂无文件</p></div>';
                return;
            }
            
            let html = '';
            files.forEach(file => {
                // 安全检查，确保是有效的文件数据
                if (!file.url || !file.name) {
                    console.warn('跳过无效文件数据:', file);
                    return;
                }
                
                const iconClass = getFileIconClass(file.type);
                const fileSize = formatFileSize(file.size || 0);
                const uploadDate = formatDate(file.putTime);
                const suffix = file.suffix || '';
                
                // 生成图标HTML，优先使用PNG图标，如果没有则使用默认的首字母图标
                const iconName = file.name.replace(/\.[^/.]+$/, ""); // 去除文件扩展名
                const iconHtml = '<img src="/icon/' + iconName + '.png" onerror="this.onerror=null; this.parentElement.innerHTML=\'' + getFileIconText(suffix) + '\';">';
                
                html += '<div class="software-card">' +
                        '<div class="software-header">' +
                        '<div class="software-icon ' + iconClass + '">' + iconHtml + '</div>' +
                        '<div class="software-info">' +
                        '<h3>' + file.name + '</h3>' +
                        '<div class="software-desc">' + fileSize + (suffix ? ' • ' + suffix.toUpperCase() : '') + '</div>' +
                        '</div>' +
                        '</div>' +
                        '<div class="software-meta">' +
                        '<div class="software-date">' + uploadDate + '</div>' +
                        '</div>' +
                        '<div class="software-actions">' +
                        '<a href="#" class="btn btn-details" onclick="showDetails(\'' + file.name + '\')">查看详情</a>' +
                        '<a href="' + getDownloadByPathUrl(file.url, file.name) + '" ' +
                        'class="btn btn-download" download="' + file.name + '">立即下载</a>' +
                        '</div>' +
                        '</div>';
            });
            
            grid.innerHTML = html;
        }
        
        function getFileIconClass(type) {
            const iconMap = {
                'image': 'icon-image',
                'document': 'icon-document', 
                'spreadsheet': 'icon-spreadsheet',
                'presentation': 'icon-presentation',
                'archive': 'icon-archive',
                'executable': 'icon-executable',
                'media': 'icon-media',
                'code': 'icon-code'
            };
            return iconMap[type] || 'icon-file';
        }
        
        function getFileIconText(suffix) {
            const iconMap = {
                'exe': 'E', 'msi': 'M', 'dmg': 'D', 'pkg': 'P',
                'zip': 'Z', 'rar': 'R', '7z': '7', 'tar': 'T',
                'pdf': 'P', 'doc': 'W', 'docx': 'W', 'xls': 'X', 'xlsx': 'X',
                'ppt': 'P', 'pptx': 'P', 'txt': 'T', 'md': 'M',
                'jpg': 'I', 'jpeg': 'I', 'png': 'I', 'gif': 'I',
                'mp3': 'A', 'mp4': 'V', 'avi': 'V', 'mov': 'V',
                'java': 'J', 'js': 'J', 'py': 'P', 'php': 'P',
                'html': 'H', 'css': 'C', 'sql': 'S', 'xml': 'X'
            };
            return iconMap[suffix.toLowerCase()] || 'F';
        }
        
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
        }
        
        function formatDate(dateString) {
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN', {
                year: 'numeric',
                month: '2-digit', 
                day: '2-digit',
                hour: '2-digit',
                minute: '2-digit'
            });
        }
        
        function showDetails(fileName) {
            alert('文件详情：' + fileName);
        }
        
        function showError(message) {
            const grid = document.getElementById('softwareGrid');
            grid.innerHTML = '<div class="empty-state"><div class="icon">⚠️</div><p>' + message + '</p></div>';
        }
        
        function showEmptyState(message) {
            const grid = document.getElementById('softwareGrid');
            grid.innerHTML = '<div class="empty-state"><div class="icon">📁</div><p>' + message + '</p></div>';
        }
        
        
        // 目录配置功能
        function toggleConfigPanel() {
            const configPanel = document.getElementById('configPanel');
            configPanel.style.display = configPanel.style.display === 'none' ? 'block' : 'none';
        }
        
        function updateDirectoryConfig() {
            const textarea = document.getElementById('knownDirectories');
            const directories = textarea.value.split('\n').filter(name => name.trim());
            
            // 保存到localStorage
            localStorage.setItem('knownDirectories', JSON.stringify(directories));
            
            alert('目录配置已更新！请刷新页面查看效果。');
        }
        
        function resetDirectoryConfig() {
            document.getElementById('knownDirectories').value = 'outlook_mail';
            localStorage.removeItem('knownDirectories');
        }
    </script>
</body>
</html>